package com.liujit.standard.basis.admin.util;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.liujit.standard.basis.core.domain.result.UserInfo;
import com.liujit.standard.basis.core.service.RedisService;
import com.liujit.standard.basis.core.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class ApiUtil {

    private static RedisService redisService;

    @Autowired
    public void setRedisService(RedisService redisService) {
        ApiUtil.redisService = redisService;
    }

    /**
     * 获取用户Id
     *
     * @return
     */
    public static Long getUserId() {
        UserInfo user = getSysUser();
        if (user == null) {
            return null;
        }
        return user.getId();
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    public static UserInfo getSysUser() {
        Map result = JwtUtils.getJWT();
        if (result == null) {
            return null;
        }
        String token = Convert.toStr(result.get("token"));
        if (StrUtil.isEmpty(token)) {
            return null;
        }
        Object o = redisService.get(token);
        if (o == null) {
            return null;
        }
        UserInfo user = (UserInfo) o;
        return user;
    }

    public static void removeToken() {
        Map result = JwtUtils.getJWT();
        if (result != null) {
            String token = Convert.toStr(result.get("token"));
            if (token != null) {
                redisService.remove(token);
            }
        }
    }
}
